import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "住院医疗保险"

    def genProductInfo(self):
        planI = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(17, 41)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 住院医疗
                "hospitalMedical": ["20000"],
                # 一般住院津贴
                "generalHosAllowance": ["80/天"],
                # 癌症住院津贴
                "cancerHosAllowance": ["100/天"],
                # 住院手术津贴
                "operationHosAllowance": ["5000"],
                # 产品计划
                "plan": ["全面款"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(17, 41)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 住院医疗
                "hospitalMedical": ["20000"],
                # 一般住院津贴
                "generalHosAllowance": ["30/天"],
                # 癌症住院津贴
                "cancerHosAllowance": ["50/天"],
                # 住院手术津贴
                "operationHosAllowance": ["5000"],
                # 产品计划
                "plan": ["热销款"]
            }

        }
        planII = {

            # 年龄段
            "year": [str(i) for i in range(17, 41)],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 保障期限
            "expire": ["1年"],
            # 交费类型
            "payType": ["年交"],
            # 住院医疗
            "hospitalMedical": ["5000", "10000", "20000"],
            # 一般住院津贴
            "generalHosAllowance": ["0", "30/天", "50/天", "80/天"],
            # 产品计划
            "plan": ["自定义"]
        }
        for k in planI:
            for v in product(planI[k]["year"], planI[k]["socialSec"], planI[k]["expire"], planI[k]["payType"],
                             planI[k]["hospitalMedical"], planI[k]["generalHosAllowance"],
                             planI[k]["cancerHosAllowance"], planI[k]["operationHosAllowance"], planI[k]["plan"]):

                data = Helper.formatProductInfo(planI[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

        for v in product(planII["year"], planII["socialSec"], planII["expire"], planII["payType"],
                         planII["hospitalMedical"], planII["generalHosAllowance"],
                         planII["plan"]):

            data = Helper.formatProductInfo( planII,v )

            if v[5] == "0":
                cancerHosAllowance = "0"
                operationHosAllowance = "0"
            elif v[5] == "30/天":
                cancerHosAllowance = "50/天"
                operationHosAllowance = "5000"
            elif v[5] == "50/天":
                cancerHosAllowance = "80/天"
                operationHosAllowance = "5000"
            else:
                cancerHosAllowance = "100/天"
                operationHosAllowance = "5000"
            data["cancerHosAllowance"] = cancerHosAllowance

            data["operationHosAllowance"] = operationHosAllowance
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( **data ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( **data ) )


    # 执行爬虫
    def requestJson(self, dt=None):
        if dt["plan"] == "全面款":
            data = {"planClass": 0, "amountFormList": [{"hospitalization": 20000, "hospitalAllowance": 3},
                                                       {"hospitalization": 20000, "hospitalAllowance": 1},
                                                       {"hospitalization": "10000", "hospitalAllowance": "0"}],
                    "beginDate": "2020-03-26", "insurantNumber": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"]))),
                    "haveSocialInsurance": "P0254B18" if dt["socialSec"] == "Y" else "P0254B19"}

            payload = json.dumps(data)
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
            if r.status_code == 200 and "quoteResult1" in r.text:
                price = r.json()["quoteResult1"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                self.mysql.updatePrice( data )
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                self.mysql.updateTask(data)
                print("\n/n产品价格更新失败:%d*/" % dt["id"])
        elif dt["plan"] == "热销款":
            data = {"planClass": 1, "amountFormList": [{"hospitalization": 20000, "hospitalAllowance": 3},
                                                       {"hospitalization": 20000, "hospitalAllowance": 1},
                                                       {"hospitalization": "10000", "hospitalAllowance": "2"}],
                    "beginDate": "2020-03-26", "insurantNumber": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"]))),
                    "haveSocialInsurance": "P0254B18" if dt["socialSec"] == "Y" else "P0254B19"}

            payload = json.dumps(data)
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
            if r.status_code == 200 and "quoteResult1" in r.text:
                price = r.json()["quoteResult2"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print(data)
                self.mysql.updatePrice(data)
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                self.mysql.updateTask(data)
                print("\n/n产品价格更新失败:%d*/" % dt["id"])
        else:

            if dt["generalHosAllowance"] == "0":

                allowance = "0"
            elif dt["generalHosAllowance"] == "30/天":
                allowance = "1"
            elif dt["generalHosAllowance"] == "50/天":
                allowance = "2"
            else:
                allowance = "3"

            data = {"planClass": 2, "amountFormList": [{"hospitalization": 20000, "hospitalAllowance": 3},
                                                       {"hospitalization": 20000, "hospitalAllowance": 1},
                                                       {"hospitalization": dt["hospitalMedical"], "hospitalAllowance": allowance}],
                    "beginDate": "2020-03-26", "insurantNumber": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"]))),
                    "haveSocialInsurance": "P0254B18" if dt["socialSec"] == "Y" else "P0254B19"}
            payload = json.dumps(data)
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
            if r.status_code == 200 and "quoteResult1" in r.text:
                price = r.json()["quoteResult3"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print(data)
                self.mysql.updatePrice(data)
            else:

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                self.mysql.updateTask( data )
                print("\n/n产品价格更新失败:%d*/"%dt["id"])
    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            print(dt)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)

